package com.easyCode.feature.result;

import com.easyCode.feature.mybaits.PageContext;
import com.easyCode.feature.mybaits.PageResult;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.util.List;


/**
 * controller返回值处理
 */
@RestControllerAdvice(annotations = ResponseResultAdvice.class)
public class ResponseAdvice implements ResponseBodyAdvice<Object> {

    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        return true;
    }
  

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        //如果存在分页信息,就进行包装
        PageResult pageInfo = PageContext.getPageInfo();
        if(pageInfo!=null && body instanceof List){
            pageInfo.setData((List<Object>) body);
            //请求结束,清除分页信息
            PageContext.clear();
            return Result.success(pageInfo);
        }
        // 提供一定的灵活度，如果body已经被包装了，就不进行包装
        if (body instanceof Result) {
            return body;
        }
        return Result.success(body);
    }
}